package util
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.utils.ByteArray;
	
	public class ImageResizer
	{
		private var loader:Loader;
		
		[Bindable]
		public var image:Bitmap;
		
		public function ImageResizer()
		{
			//TODO: implement function
		}
		
		public function scaleTo(bytes:ByteArray,resizeComplete:Function,width:uint,height:uint):void
		{
			if(loader == null)
				loader = new Loader();
			loader.loadBytes(bytes);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadCompleted);
			
		}
		
		protected function loadCompleted(e:Event):void
		{
			image = Bitmap(loader.content);
			var bdata:BitmapData = image.bitmapData;
			var scaleFactor:Number = 1;
			var scaleFactory:Number = 1;
			
			//if(bdata.width > bdata.height)
				scaleFactor = 48/bdata.width
			//else
				scaleFactory = 48/bdata.height;
				
			var newWidth:Number = scaleFactor*bdata.width;
			var newHeight:Number = scaleFactor*bdata.height;
			
			var scaledImg:BitmapData = new BitmapData(48,48);
			var scaledMatrix:Matrix = new Matrix();
			scaledMatrix.scale(scaleFactor,scaleFactory);
			
			scaledImg.draw(image,scaledMatrix,null,null,null,true);
			
			image.bitmapData = scaledImg
			image.smoothing=true;
		}
		
		public function scaleImageTo(img:Bitmap,widthTo:uint,heightTo:uint):void
		{
			var bdata:BitmapData = img.bitmapData;
			var scaleFactor:Number = 1;
			var scaleFactory:Number = 1;
			
			//if(bdata.width > bdata.height)
				scaleFactor = widthTo/bdata.width
			//else
				scaleFactory = heightTo/bdata.height;
				
			var newWidth:uint = scaleFactor*bdata.width;
			var newHeight:uint = scaleFactor*bdata.height;
			
			var scaledImg:BitmapData = new BitmapData(widthTo,heightTo);
			var scaledMatrix:Matrix = new Matrix();
			scaledMatrix.scale(scaleFactor,scaleFactory);
			
			scaledImg.draw(img,scaledMatrix,null,null,null,true);
			
			img.bitmapData = scaledImg
			//img.smoothing=true;
		}

	}
}